<template>
  <div class="warn-rule-container">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-table :data="tableData" border style="width: 100%; margin-top: 20px">
      <el-table-column
        prop="index"
        label="序号"
        type="index"
        width="50"
      ></el-table-column>
      <el-table-column prop="itemname" label="预警因子"></el-table-column>
      <el-table-column prop="symbol" label="类型">
        <template slot-scope="scope">
          {{ getSymbolText(scope.row.symbol) }}
        </template>
      </el-table-column>
      <el-table-column prop="numvalue" label="预警值"></el-table-column>
      <el-table-column prop="isEnabled" label="是否启用">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isno"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑弹窗 -->
    <el-dialog title="编辑预警规则" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="预警因子" prop="conditionname">
          <el-select
            v-model="form.conditionname"
            placeholder="请选择预警因子"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.itemCode"
              :label="item.itemName"
              :value="item.itemCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="symbol">
          <el-select
            v-model="form.symbol"
            placeholder="请选择类型"
            style="width: 100%"
            clearable
          >
            <el-option label="大于等于" value="1"></el-option>
            <el-option label="大于" value="2"></el-option>
            <el-option label="小于等于" value="3"></el-option>
            <el-option label="小于" value="4"></el-option>
            <el-option label="等于" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预警值" prop="numvalue">
          <el-input
            v-model.number="form.numvalue"
            placeholder="请输入预警值"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getFactorList } from "@/api/commonApi";
import {
  getWarningRule,
  updateWarningRule,
  updateWarningFactor,
  addWarningFactor,
  deleteWarningFactor,
  enableWarningFactor,
  closeWarningFactor,
  getWarningFactorById,
} from "@/api/waterWarningAnalysis";
export default {
  data() {
    return {
      tableData: [],
      options: [],
      dialogVisible: false,
      form: {
        id: "", // 用于区分新增/修改的标识
        conditionname: "",
        symbol: "",
        numvalue: null,
        isno: "0", // 默认启用
      },
      currentRow: null,
      symbolMap: {
        1: "大于等于",
        2: "大于",
        3: "小于等于",
        4: "小于",
        5: "等于",
      },
      // 表单校验规则
      rules: {
        conditionname: [
          { required: true, message: "请选择预警因子", trigger: "change" },
        ],
        symbol: [{ required: true, message: "请选择类型", trigger: "change" }],
        numvalue: [
          { required: true, message: "请输入预警值", trigger: "blur" },
        ],
      },
      nowid: "",
    };
  },
  created() {
    this.getFactorList();
    this.getWarningRule();
  },
  methods: {
    // 获取污染因子
    getFactorList() {
      getFactorList({ bussinessCategoryCode: "CBN" }).then((res) => {
        this.options = res.data || [];
      });
    },

    // 获取预警规则数据
    getWarningRule() {
      getWarningRule({ warntype: "101" })
        .then((res) => {
          this.tableData = res.data?.[0]?.busWaterWarnruleConditionsList || [];
          this.nowid = res.data?.[0]?.id;
        })
        .catch((err) => {
          console.error("获取规则数据失败:", err);
        });
    },

    // 符号转换文本
    getSymbolText(symbol) {
      return this.symbolMap[symbol] || "";
    },

    // 状态切换
    handleStatusChange(row) {
      const text = row.isno === "0" ? "启用" : "停用";
      this.$modal
        .confirm(`确认要${text}"${row.itemname}"吗？`)
        .then(() => {
          return row.isno === "0"
            ? enableWarningFactor(row.id)
            : closeWarningFactor(row.id);
        })
        .then(() => {
          this.$modal.msgSuccess(`${text}成功`);
        })
        .catch(() => {
          // 操作取消时恢复原始状态
          row.isno = row.isno === "0" ? "1" : "0";
        });
    },

    // 新增
    handleAdd() {
      this.dialogVisible = true;
      this.currentRow = null;
      // 清空表单
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.form = {
          id: "",
          conditionname: "",
          symbol: "",
          numvalue: null,
          isno: "0",
        };
      });
    },

    // 编辑
    handleEdit(row) {
      this.dialogVisible = true;
      this.currentRow = row;
      // 获取详情数据
      getWarningFactorById(row.id).then((res) => {
        this.form = { ...res.data };
      });
    },

    // 删除
    handleDelete(row) {
      this.$confirm("确定要删除这条预警规则吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          return deleteWarningFactor(row.id);
        })
        .then(() => {
          this.$message.success("删除成功!");
          this.getWarningRule(); // 重新获取列表
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 保存（新增/修改）
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 表单验证通过
          let requestData = { ...this.form };

          // 区分新增和修改
          if (!requestData.id) {
            // 新增时添加 ruleid 字段，值为 nowid
            requestData = { ...requestData, ruleid: this.nowid };
          }

          const promise = requestData.id
            ? updateWarningFactor(requestData)
            : addWarningFactor(requestData);

          promise
            .then(() => {
              this.$message.success(requestData.id ? "修改成功" : "新增成功");
              this.dialogVisible = false;
              this.getWarningRule(); // 重新获取列表
            })
            .catch((err) => {
              console.error("操作失败:", err);
              this.$message.error(requestData.id ? "修改失败" : "新增失败");
            });
        }
      });
    },
  },
};
</script>

<style scoped>
.warn-rule-container {
  padding: 20px;
  background-color: #fff;
}
</style>
